package cmd

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/gcmd"
	"github.com/gogf/gf/v2/os/gproc"
	"github.com/gogf/gf/v2/os/gsession"
	"server/internal/router"
	"server/internal/service"
)

var (
	Http = &gcmd.Command{
		Name:  "http",
		Usage: "http",
		Brief: "Http服务",
		Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
			g.Log().Debugf(ctx, "http server start, process id %v", gproc.Pid())

			s := g.Server()
			s.EnableAdmin()

			//s.SetDumpRouterMap(false)

			//全局_前置中间件
			s.Use(ghttp.MiddlewareCORS)

			// Session-Redis
			s.SetSessionStorage(gsession.NewStorageRedis(g.Redis()))
			//s.SetSessionMaxAge(time.Minute)

			s.Group("/", func(group *ghttp.RouterGroup) {
				// 注册后台路由
				router.Admin(ctx, group)

				// 注册前台路由v1版本
				router.V1(ctx, group)
			})

			// 系统服务器监控，数据通过websocket推送至客户端展示
			service.SystemMonitor().StartMonitor(ctx)

			// 注册 websocket 路由
			router.Websocket(ctx, s)

			//静态文件服务
			if config, err := service.File().GetFileUploadConfig(ctx); err != nil {
				g.Log().Debug(ctx, err)
			} else if len(config.Local.FileServerStaticURIPath) > 0 {
				//是否允许展示访问目录的文件列表
				s.SetIndexFolder(config.Local.FileServerEnabledIndexFolder)

				//添加URI与静态目录的映射
				s.AddStaticPath(config.Local.FileServerStaticURIPath, config.Local.FileServerDIR)
			}

			serverWg.Add(1)

			// 监听进程退出的信号
			signalListen(ctx, signalHandlerForOverall)

			go func() {
				<-serverCloseSignal
				serverWg.Done()
				g.Log().Debug(ctx, "http server closed")
			}()

			s.Run()

			return nil
		},
	}
)
